<template>
  <div class="oneway-flight-detail">
    <!-- 航班基本信息 -->
    <el-card shadow="never" class="detail-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            单程航班详情
          </span>
          <div class="flight-tags">
            <el-tag v-if="flight.transferCount === 0" type="success" size="small">
              直飞
            </el-tag>
            <el-tag v-else type="warning" size="small">
              {{ flight.transferCount }}次中转
            </el-tag>
          </div>
        </div>
      </template>

      <div class="flight-overview">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">航班号：</span>
              <span class="value highlight">{{ flight.flightNumber }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">航空公司：</span>
              <span class="value">{{ flight.airline || getAirlineName(flight.airlineCode) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">飞行时长：</span>
              <span class="value">{{ flight.duration }}</span>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-top: 16px;">
          <el-col :span="12">
            <div class="route-summary">
              <div class="route-info">
                <span class="departure-city">{{ getDepartureInfo() }}</span>
                <el-icon class="route-arrow"><Right /></el-icon>
                <span class="arrival-city">{{ getArrivalInfo() }}</span>
              </div>
              <div class="airport-info">
                {{ flight.departureAirport || getAirportName(flight.departureAirportCode) }}
                →
                {{ flight.arrivalAirport || getAirportName(flight.arrivalAirportCode) }}
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="price-summary">
              <div class="price-main">
                <span class="currency">{{ flight.currency }}</span>
                <span class="amount">{{ flight.adultTotalPrice }}</span>
              </div>
              <div class="price-detail">
                基础价格: {{ flight.adultPrice }} + 税费: {{ flight.adultTax }}
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 详细航程信息 -->
    <el-card shadow="never" class="detail-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            详细航程
          </span>
          <el-tag type="info" size="small">
            {{ getSegmentCount() }} 个航段
          </el-tag>
        </div>
      </template>

      <!-- 如果有详细航段信息 -->
      <div v-if="hasDetailedSegments()" class="detailed-segments">
        <div
            v-for="(segment, index) in getDetailedSegments()"
            :key="index"
            class="segment-item">
          <!-- 航段标题 -->
          <div class="segment-header">
            <div class="segment-number">
              <el-tag size="small" type="primary">航段 {{ index + 1 }}</el-tag>
            </div>
            <div class="segment-flight">
              <span class="flight-no">{{ segment.flightNo }}</span>
              <span class="airline">{{ getAirlineName(segment.airlineCode) }}</span>
              <el-tag size="mini" type="info">{{ segment.seatClass }}</el-tag>
            </div>
          </div>

          <!-- 航段路线 -->
          <div class="segment-route">
            <!-- 出发信息 -->
            <div class="route-point departure">
              <div class="time-info">
                <div class="time">{{ formatTime(segment.departureDateTime) }}</div>
                <div class="date">{{ formatDate(segment.departureDateTime) }}</div>
              </div>
              <div class="location-info">
                <div class="airport">{{ getAirportName(segment.departureAirportCode) }}</div>
                <div class="city">{{ getCityName(segment.departureCityCode) }}</div>
                <div class="terminal" v-if="segment.departureTerminal">
                  {{ segment.departureTerminal }}
                </div>
              </div>
            </div>

            <!-- 飞行路径 -->
            <div class="flight-path">
              <div class="path-line">
                <el-icon><Right /></el-icon>
              </div>
              <div class="flight-info">
                <div class="flight-duration">{{ calculateSegmentDuration(segment) }}</div>
              </div>
            </div>

            <!-- 到达信息 -->
            <div class="route-point arrival">
              <div class="time-info">
                <div class="time">{{ formatTime(segment.arrivalDateTime) }}</div>
                <div class="date">{{ formatDate(segment.arrivalDateTime) }}</div>
              </div>
              <div class="location-info">
                <div class="airport">{{ getAirportName(segment.arrivalAirportCode) }}</div>
                <div class="city">{{ getCityName(segment.arrivalCityCode) }}</div>
                <div class="terminal" v-if="segment.arrivalTerminal">
                  {{ segment.arrivalTerminal }}
                </div>
              </div>
            </div>
          </div>

          <!-- 中转等待时间 -->
          <div
              v-if="index < getDetailedSegments().length - 1"
              class="transfer-info">
            <div class="transfer-indicator">
              <el-icon><Clock /></el-icon>
              <span class="transfer-text">中转等待</span>
            </div>
            <div class="transfer-duration">
              {{ calculateTransferTime(segment, getDetailedSegments()[index + 1]) }}
            </div>
            <div class="transfer-location">
              在 {{ getCityName(segment.arrivalCityCode) }}
              ({{ getAirportName(segment.arrivalAirportCode) }}) 中转
            </div>
          </div>
        </div>
      </div>

      <!-- 如果没有详细航段信息，显示简化信息 -->
      <div v-else class="simplified-route">
        <div class="route-timeline">
          <div class="route-point departure">
            <div class="time-info">
              <div class="time">{{ formatTime(flight.departureTime) }}</div>
              <div class="date">{{ formatDate(flight.departureTime) }}</div>
            </div>
            <div class="location-info">
              <div class="airport">{{ flight.departureAirport || getAirportName(flight.departureAirportCode) }}</div>
              <div class="city">{{ flight.departureCity || getCityName(flight.departureCityCode) }}</div>
              <div class="terminal" v-if="flight.departureTerminal">{{ flight.departureTerminal }}</div>
            </div>
          </div>

          <div class="route-line">
            <div class="flight-path">
              <el-icon><Right /></el-icon>
              <span class="duration">{{ flight.duration }}</span>
              <span v-if="flight.transferCount > 0" class="stops">{{ flight.transferCount }}次中转</span>
              <span v-else class="direct">直飞</span>
            </div>
          </div>

          <div class="route-point arrival">
            <div class="time-info">
              <div class="time">{{ formatTime(flight.arrivalTime) }}</div>
              <div class="date">{{ formatDate(flight.arrivalTime) }}</div>
              <div v-if="flight.crossDays > 0" class="cross-days">+{{ flight.crossDays }}天</div>
            </div>
            <div class="location-info">
              <div class="airport">{{ flight.arrivalAirport || getAirportName(flight.arrivalAirportCode) }}</div>
              <div class="city">{{ flight.arrivalCity || getCityName(flight.arrivalCityCode) }}</div>
              <div class="terminal" v-if="flight.arrivalTerminal">{{ flight.arrivalTerminal }}</div>
            </div>
          </div>
        </div>

        <!-- 中转提示 -->
        <div v-if="flight.transferCount > 0" class="transfer-hint">
          <el-alert
              title="中转航班提示"
              type="warning"
              :closable="false"
              show-icon>
            <template #default>
              <p>此航班包含 {{ flight.transferCount }} 次中转，具体中转机场信息请咨询航空公司。</p>
              <p v-if="flight.flightNumber && flight.flightNumber.includes('+')" class="multiple-flights">
                涉及多个航班：{{ flight.flightNumber }}
              </p>
            </template>
          </el-alert>
        </div>
      </div>
    </el-card>

    <!-- 价格信息 -->
    <el-card shadow="never" class="detail-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><Money /></el-icon>
            价格信息
          </span>
        </div>
      </template>

      <div class="price-details">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="price-breakdown">
              <h4>成人价格</h4>
              <div class="price-line">
                <span>基础价格：</span>
                <span class="price">{{ flight.currency }} {{ flight.adultPrice || 0 }}</span>
              </div>
              <div class="price-line">
                <span>税费：</span>
                <span class="price">{{ flight.currency }} {{ flight.adultTax || 0 }}</span>
              </div>
              <el-divider></el-divider>
              <div class="price-line total">
                <span>总价：</span>
                <span class="price highlight">{{ flight.currency }} {{ flight.adultTotalPrice }}</span>
              </div>
            </div>
          </el-col>
          <el-col :span="12" v-if="hasChildPrice()">
            <div class="price-breakdown">
              <h4>儿童价格</h4>
              <div class="price-line">
                <span>基础价格：</span>
                <span class="price">{{ flight.currency }} {{ flight.childPrice || 0 }}</span>
              </div>
              <div class="price-line">
                <span>税费：</span>
                <span class="price">{{ flight.currency }} {{ flight.childTax || 0 }}</span>
              </div>
              <el-divider></el-divider>
              <div class="price-line total">
                <span>总价：</span>
                <span class="price highlight">{{ flight.currency }} {{ flight.childTotalPrice }}</span>
              </div>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="hasInfantPrice()" style="margin-top: 20px;">
          <el-col :span="12">
            <div class="price-breakdown">
              <h4>婴儿价格</h4>
              <div class="price-line">
                <span>基础价格：</span>
                <span class="price">{{ flight.currency }} {{ flight.infantPrice || 0 }}</span>
              </div>
              <div class="price-line">
                <span>税费：</span>
                <span class="price">{{ flight.currency }} {{ flight.infantTax || 0 }}</span>
              </div>
              <el-divider></el-divider>
              <div class="price-line total">
                <span>总价：</span>
                <span class="price highlight">{{ flight.currency }} {{ flight.infantTotalPrice }}</span>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 服务信息 -->
    <el-card shadow="never" class="detail-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><Service /></el-icon>
            服务信息
          </span>
        </div>
      </template>

      <div class="service-info">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-section">
              <h4>行李信息</h4>
              <p class="baggage-info">{{ flight.baggageInfo || '请咨询航空公司' }}</p>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-section">
              <h4>购买须知</h4>
              <p class="policy-info">{{ getPurchaseNotes() }}</p>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">舱位等级：</span>
              <el-tag size="small" :type="getCabinType()">{{ getCabinLabel() }}</el-tag>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">余票数量：</span>
              <span class="value">{{ flight.ticketCount || '充足' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">最后更新：</span>
              <span class="value">{{ formatDateTime(flight.lastUpdated) }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import {
  Money,
  Service,
  Right,
  Clock,
} from '@element-plus/icons-vue'
import cityNames from "@/utils/cityNames.js"
import airportNames from "@/utils/airportNames.js"
import airlineNames from "@/utils/airlineNames.js"

// Props
const props = defineProps({
  flight: {
    type: Object,
    required: true
  }
})

// 方法
const getDepartureInfo = () => {
  return `${props.flight.departureCity || getCityName(props.flight.departureCityCode)} (${props.flight.departureAirportCode})`
}

const getArrivalInfo = () => {
  return `${props.flight.arrivalCity || getCityName(props.flight.arrivalCityCode)} (${props.flight.arrivalAirportCode})`
}

const hasDetailedSegments = () => {
  return props.flight.segments && props.flight.segments.length > 0
}

const getDetailedSegments = () => {
  return props.flight.segments || []
}

const getSegmentCount = () => {
  if (hasDetailedSegments()) {
    return getDetailedSegments().length
  }
  return (props.flight.transferCount || 0) + 1
}

const calculateSegmentDuration = (segment) => {
  try {
    const departure = new Date(segment.departureDateTime)
    const arrival = new Date(segment.arrivalDateTime)
    const duration = Math.round((arrival - departure) / (1000 * 60))

    if (duration < 60) {
      return `${duration}分钟`
    } else {
      const hours = Math.floor(duration / 60)
      const minutes = duration % 60
      return minutes > 0 ? `${hours}小时${minutes}分钟` : `${hours}小时`
    }
  } catch (e) {
    return '时长待确认'
  }
}

const calculateTransferTime = (currentSegment, nextSegment) => {
  try {
    const arrivalTime = new Date(currentSegment.arrivalDateTime)
    const departureTime = new Date(nextSegment.departureDateTime)
    const transferMinutes = Math.round((departureTime - arrivalTime) / (1000 * 60))

    if (transferMinutes < 60) {
      return `${transferMinutes}分钟`
    } else {
      const hours = Math.floor(transferMinutes / 60)
      const minutes = transferMinutes % 60
      return minutes > 0 ? `${hours}小时${minutes}分钟` : `${hours}小时`
    }
  } catch (e) {
    return '等待时间待确认'
  }
}

const hasChildPrice = () => {
  return props.flight.childPrice && props.flight.childPrice > 0
}

const hasInfantPrice = () => {
  return props.flight.infantPrice && props.flight.infantPrice > 0
}

const formatTime = (dateTimeStr) => {
  if (!dateTimeStr) return '--'
  try {
    return dateTimeStr.substring(11, 16)
  } catch (e) {
    return dateTimeStr
  }
}

const formatDate = (dateTimeStr) => {
  if (!dateTimeStr) return '--'
  try {
    return dateTimeStr.substring(5, 10)
  } catch (e) {
    return dateTimeStr
  }
}

const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '--'
  try {
    return dateTimeStr.substring(0, 16).replace('T', ' ')
  } catch (e) {
    return dateTimeStr
  }
}

const getCabinType = () => {
  const typeMap = {
    'Y': 'success',
    'Y_S': 'success',
    'C': 'warning',
    'C_S': 'warning',
    'F': 'danger',
    'F_S': 'danger'
  }
  return typeMap[props.flight.cabinClass] || 'info'
}

const getCabinLabel = () => {
  const labelMap = {
    'Y': '经济舱',
    'Y_S': '经济舱',
    'C': '商务舱',
    'C_S': '商务舱',
    'F': '头等舱',
    'F_S': '头等舱'
  }
  return labelMap[props.flight.cabinClass] || props.flight.cabinClass
}

const getPurchaseNotes = () => {
  const notes = props.flight.purchaseNotes
  if (Array.isArray(notes)) {
    return notes.join('; ')
  }
  return notes || '请咨询航空公司'
}

const getAirlineName = (airlineCode) => {
  return airlineNames[airlineCode] || airlineCode
}

const getAirportName = (airportCode) => {
  return airportNames[airportCode] || airportCode
}

const getCityName = (cityCode) => {
  return cityNames[cityCode] || cityCode
}
</script>

<style scoped>
.oneway-flight-detail {
  max-width: 1000px;
  margin: 0 auto;
}

.detail-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: bold;
}

.flight-tags {
  display: flex;
  gap: 8px;
}

.flight-overview {
  padding: 0;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.info-item .label {
  min-width: 80px;
  color: #666;
  font-size: 14px;
}

.info-item .value {
  font-size: 14px;
  color: #333;
}

.info-item .value.highlight {
  font-weight: bold;
  color: #409eff;
}

.route-summary {
  text-align: center;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.route-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 8px;
}

.departure-city,
.arrival-city {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
}

.route-arrow {
  color: #67c23a;
  font-size: 20px;
}

.airport-info {
  font-size: 13px;
  color: #666;
}

.price-summary {
  text-align: center;
  padding: 16px;
  background-color: #fff7e6;
  border-radius: 8px;
  border: 2px solid #ffd591;
}

.price-main {
  margin-bottom: 8px;
}

.currency {
  font-size: 14px;
  color: #999;
}

.amount {
  font-size: 24px;
  font-weight: bold;
  color: #fa541c;
  margin-left: 4px;
}

.price-detail {
  font-size: 12px;
  color: #666;
}

/* 详细航段样式 */
.detailed-segments {
  padding: 0;
}

.segment-item {
  margin-bottom: 24px;
  padding: 20px;
  border: 1px solid #e8e8e8;
  border-radius: 12px;
  background-color: #fafafa;
}

.segment-item:last-child {
  margin-bottom: 0;
}

.segment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e8e8e8;
}

.segment-flight {
  display: flex;
  align-items: center;
  gap: 12px;
}

.flight-no {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
}

.airline {
  font-size: 14px;
  color: #666;
}

.segment-route {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.route-point {
  flex: 1;
  text-align: center;
}

.route-point.departure {
  text-align: left;
}

.route-point.arrival {
  text-align: right;
}

.time-info {
  margin-bottom: 12px;
}

.time {
  font-size: 20px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 4px;
}

.date {
  font-size: 12px;
  color: #999;
}

.cross-days {
  font-size: 11px;
  color: #f56c6c;
  font-weight: bold;
}

.location-info {
  padding: 12px;
  background-color: white;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.airport {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.city {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.terminal {
  font-size: 11px;
  color: #999;
  background-color: #f0f0f0;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
}

.flight-path {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 20px;
}

.path-line {
  color: #67c23a;
  font-size: 24px;
  margin-bottom: 8px;
}

.flight-info {
  text-align: center;
  background-color: white;
  padding: 8px 12px;
  border-radius: 20px;
  border: 2px solid #67c23a;
}

.flight-duration {
  font-size: 12px;
  font-weight: bold;
  color: #67c23a;
}

/* 中转信息样式 */
.transfer-info {
  background-color: #fff7e6;
  border: 1px solid #ffd591;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
  position: relative;
}

.transfer-info::before {
  content: '';
  position: absolute;
  top: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 10px solid #ffd591;
}

.transfer-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-bottom: 8px;
}

.transfer-text {
  font-size: 14px;
  font-weight: bold;
  color: #fa8c16;
}

.transfer-duration {
  font-size: 16px;
  font-weight: bold;
  color: #fa541c;
  margin-bottom: 4px;
}

.transfer-location {
  font-size: 12px;
  color: #666;
}

/* 简化路线样式 */
.simplified-route {
  padding: 0;
}

.route-timeline {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 0;
  position: relative;
}

.route-line {
  flex: 2;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.route-line::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 20px;
  right: 20px;
  height: 2px;
  background: linear-gradient(to right, #409eff, #67c23a);
  transform: translateY(-50%);
  z-index: 1;
}

.flight-path {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  background-color: white;
  padding: 12px 20px;
  border-radius: 20px;
  border: 2px solid #409eff;
  position: relative;
  z-index: 2;
}

.flight-path .duration {
  font-size: 14px;
  font-weight: bold;
  color: #409eff;
}

.flight-path .stops {
  font-size: 12px;
  color: #f56c6c;
}

.flight-path .direct {
  font-size: 12px;
  color: #67c23a;
}

.transfer-hint {
  margin-top: 20px;
}

.multiple-flights {
  margin-top: 8px;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  color: #409eff;
}

/* 价格详情样式 */
.price-details {
  padding: 0;
}

.price-breakdown {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background-color: #fafafa;
}

.price-breakdown h4 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 16px;
}

.price-line {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.price-line.total {
  font-weight: bold;
  font-size: 16px;
  margin-top: 8px;
}

.price-line .price {
  font-family: 'Courier New', monospace;
}

.price-line .price.highlight {
  color: #f56c6c;
  font-weight: bold;
}

/* 服务信息样式 */
.service-info {
  padding: 0;
}

.info-section {
  margin-bottom: 16px;
}

.info-section h4 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 14px;
}

.baggage-info, .policy-info {
  font-size: 13px;
  color: #666;
  line-height: 1.5;
  margin: 0;
  padding: 8px 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .oneway-flight-detail {
    padding: 0 10px;
  }

  .route-timeline {
    flex-direction: column;
    gap: 20px;
  }

  .route-line {
    width: 100%;
    height: 60px;
  }

  .route-line::before {
    left: 50%;
    right: auto;
    width: 2px;
    height: 40px;
    top: 10px;
    transform: translateX(-50%);
    background: linear-gradient(to bottom, #409eff, #67c23a);
  }

  .route-point {
    width: 100%;
    text-align: center !important;
  }

  .segment-route {
    flex-direction: column;
    gap: 16px;
  }

  .flight-path {
    margin: 0;
    width: 100%;
  }

  .path-line {
    transform: rotate(90deg);
  }

  .route-info {
    flex-direction: column;
    gap: 8px;
  }

  .route-arrow {
    transform: rotate(90deg);
  }

  .segment-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
}
</style>